﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Net.Mail;
using System.Web.Security;
using System.IO;
using System.Data.SqlClient;

/// <summary>
/// Summary description for TicketBAL
/// </summary>
public class TicketBAL
{
    private TicketDAL _ticketDAL;
    public TicketBAL()
    {
        _ticketDAL = new TicketDAL();
    }

    public void checkBookedTickets(object sender)
    {
        HttpContext x = sender as HttpContext;
        string ThreeWeeksMailBody = x.Server.MapPath("~/MailTemplate/BookTicketReminder.txt");
        string TwoWeeksMailBody = x.Server.MapPath("~/MailTemplate/BookTicketExpired.txt");

        int ticketID;
        string username;
        string email;
        MembershipUser user;
        DataSet ds;
        SmtpClient client;
        client = new SmtpClient("smtp.gmail.com", 587);
        client.EnableSsl = true;
        MailMessage message;
        message = new MailMessage();
        message.From = new MailAddress("anhvhb00319@gmail.com", "Airline Reservation Team");
        message.IsBodyHtml = false;

        ds = _ticketDAL.getBookedTicketbyDate(21);
        if (ds != null)
        {
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                user = Membership.GetUser(row["UserID"]);
                username = user.UserName;
                email = user.Email;
                ticketID = Convert.ToInt32(row["TicketID"]);
                message.To.Clear();
                message.To.Add(new MailAddress(email));
                message.Subject = "Your Booked Ticket is about to expired";
                message.Body = File.OpenText(ThreeWeeksMailBody).ReadToEnd();
                message.Body = message.Body.Replace("<%UserName%>", username);
                message.Body = message.Body.Replace("<%TicketID%>", ticketID.ToString());

                client.Send(message);
            }
            ds.Clear();
        }

        ds = _ticketDAL.getBookedTicketbyDate(14);
        if (ds != null)
        {
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                user = Membership.GetUser(row["UserID"]);
                username = user.UserName;
                email = user.Email;
                ticketID = Convert.ToInt32(row["TicketID"]);

                _ticketDAL.ExpiredTicket(ticketID);

                message.To.Clear();
                message.To.Add(new MailAddress(email));
                message.Subject = "Your Booked Ticket is Expired";
                message.Body = message.Body = File.OpenText(TwoWeeksMailBody).ReadToEnd();
                message.Body = message.Body.Replace("<%UserName%>", username);
                message.Body = message.Body.Replace("<%TicketID%>", ticketID.ToString());

                client.Send(message);
            }
        }
    }

    public int getDiscount(DateTime departtime, string type)
    {
        return _ticketDAL.getDiscount(departtime, type);
    }

    public Ticket getByID(int ticketID)
    {
        DataSet ds = _ticketDAL.getTicketByID(ticketID);
        if (ds.Tables.Count == 1)
        {
            List<Ticket> ticketlist = ConvertDataTabelToTickets(ds.Tables[0]);
            if (ticketlist.Count == 1)
            {
                return ticketlist[0];
            }
            else
            {
                return null;
            }
        }
        else
        {
            return null;
        }
    }

    public List<TicketDetail> getTicketDetail(int ticketid)
    {
        DataSet ds = _ticketDAL.getTicketDetail(ticketid);
        if (ds.Tables.Count == 1)
        {
            List<TicketDetail> detail = ConvertDataTabelToTicketDetails(ds.Tables[0]);
            if (detail.Count > 0)
            {
                return detail;
            }
            else
            {
                return null;
            }
        }
        else
        {
            return null;
        }
    }

    private List<TicketDetail> ConvertDataTabelToTicketDetails(DataTable dt)
    {
        List<TicketDetail> DetailList = new List<TicketDetail>();
        if (dt.Rows.Count > 0)
        {
            foreach (DataRow row in dt.Rows)
            {
                TicketDetail detail = new TicketDetail();
                detail.ID = Convert.ToInt32(row["TicketDetailID"]); 
                detail.Price = Convert.ToInt32(row["Price"]);
                detail.SeatClass = Convert.ToString(row["SeatClass"]); 
                detail.Passenger.Age = Convert.ToInt32(row["Age"]);
                detail.Passenger.FirstName = Convert.ToString(row["First Name"]); 
                detail.Passenger.IsMale = Convert.ToBoolean(row["IsMale"]); 
                detail.Passenger.LastName = Convert.ToString(row["Last Name"]);

                DetailList.Add(detail);
            }
        }
        return DetailList;
    }

    private List<Ticket> ConvertDataTabelToTickets(DataTable dt)
    {
        List<Ticket> TiicketList = new List<Ticket>();
        if (dt.Rows.Count > 0)
        {
            foreach (DataRow row in dt.Rows)
            {
                Ticket ticket = new Ticket();
                ticket.ID = Convert.ToInt32(row["TicketID"]);
                ticket.UserID = Convert.ToString(row["UserID"]);
                ticket.BoughtDay = Convert.ToDateTime(row["BoughtDay"]);
                ticket.Flight.FlightID = Convert.ToInt32(row["FlightID"]);
                ticket.Flight.DepartTime = Convert.ToDateTime(row["Depart Time"]);
                ticket.Flight.FlyHour = Convert.ToDouble(row["FlyHour"]);
                ticket.Flight.Route.Origin.ID = Convert.ToInt32(row["OriginalCityID"]);
                ticket.Flight.Route.Destination.ID = Convert.ToInt32(row["DestinationCityID"]);
                ticket.Status = Convert.ToString(row["TicketStatus"]);
                TiicketList.Add(ticket);
            }
        }
        return TiicketList;
    }

    public List<double> NewTicket(List<Ticket> TicketList, string request, string userid)
    {
        List<double> output = new List<double>();
        int ticketID = 0;
        FlightBAL _flightBAL = new FlightBAL();
        double distance = 0;
        foreach (Ticket ticket in TicketList)
        {
            Passenger firstpass = ticket.TicketDetail[0].Passenger;
            ticketID = _ticketDAL.NewTicket(userid, ticket.Flight.FlightID, request, firstpass.FirstName, firstpass.LastName, firstpass.Age.ToString(), firstpass.IsMale, ticket.TicketDetail[0].SeatClass, ticket.TicketDetail[0].Price);
            distance += _flightBAL.calDistance(ticket.Flight.Route.Origin, ticket.Flight.Route.Destination);
            output.Add(ticketID);
            if (ticketID <= 0)
            {
                output.Add(-1);
                return output;
            }
            if (ticket.TicketDetail.Count > 1)
            {

                for (int i = 1; i < ticket.TicketDetail.Count; i++)
                {
                    ticketID = _ticketDAL.FillTicketDetail(ticketID, ticket.TicketDetail[i].Passenger.FirstName, ticket.TicketDetail[i].Passenger.LastName, ticket.TicketDetail[i].Passenger.Age.ToString(), ticket.TicketDetail[i].Passenger.IsMale, ticket.TicketDetail[i].SeatClass, ticket.TicketDetail[i].Price);

                    if (ticketID <= 0)
                    {
                        output.Add(-1);
                        return output;
                    }
                }
            }
        }
        output.Add(distance);
        return output;
    }

    public bool changeTicketStatus(String status, String ticketID)
    {
        SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["sqlString"].ConnectionString);
        con.Open();
        String sqlCommand = "Update [Airline_Ticket] set [TicketStatus] = '" + status + "' where [TicketID] = " + ticketID;
        bool flag = false;
        try
        {
            SqlCommand com = new SqlCommand(sqlCommand, con);
            int rows = com.ExecuteNonQuery();
            if (rows > 0)
            {
                flag = true;
            }
        }
        catch (Exception)
        {
        }
        finally
        {
            con.Close();
        }
        return flag;
    }

    public bool checkTicket(string userid, int ticketid, string status)
    {
        return _ticketDAL.checkTicket(ticketid, userid, status);
    }

    public int cancelTicket(int ticketid)
    {
        return _ticketDAL.CancelTicket(ticketid);
    }

    public void ConfirmTicket(Ticket ticket, string userid)
    {
        _ticketDAL.confirmTicket(ticket.ID);
        foreach (TicketDetail detail in ticket.TicketDetail)
        {
            _ticketDAL.confirmDetail(detail.ID, detail.Price);
        }
    }

    public List<double> RescheduleTicket(Ticket oldTicket, Ticket newTicket,string userid)
    {
        cancelTicket(oldTicket.ID);
        List<Ticket> temp = new List<Ticket>();
        temp.Add(newTicket);
        return NewTicket(temp, "Buy", userid);
    }
}
